package com.hs.mod_archive.helper

import android.content.Context
import android.database.Cursor
import android.graphics.Color
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import com.hs.framework.helper.HsAppHelper.getApplication
import com.hs.mod_archive.R
import com.hs.mod_archive.view.MyListView
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

open class ListViewHelper(
    var mFootPageView: MyListView?,
    private var mFootSearchCallback: FootSearchCallback?
) {
    var currentIndex: Int = 0
    var mTotalItemCountInDatabase: Int = 0
    var mMaxPageCount: Int = 0
    var yearMonthDay: SimpleDateFormat = SimpleDateFormat(yearMonthDayStr, Locale.US)

    val mColorBgOddNumberLine: Int

    init {
        mFootPageView!!.mBtFirstPage.setOnClickListener {
            showFirstPage()
        }
        mFootPageView!!.mBtToPreviousPage.setOnClickListener {
            helperActionSearch(currentIndex - 1)
        }
        mFootPageView!!.mBtToNextPage.setOnClickListener {
            helperActionSearch(currentIndex + 1)
        }
        mFootPageView!!.mBtLastPage.setOnClickListener {
            showLastPage()
        }
        mColorBgOddNumberLine =
            Color.parseColor("#F2F2F2") // footPageListView.getContext().getResources().getColor(R.color.bg_list_view_item_single);

        mFootPageView!!.mBtJumpTo.setOnClickListener { v: View? ->
            val jumpToValue =
                mFootPageView!!.mEtJumpToValue.text.toString().trim { it <= ' ' }
            val jumpToNewPage: Int
            try {
                jumpToNewPage = jumpToValue.toInt()
                helperActionSearch(jumpToNewPage - 1)
            } catch (e: Exception) {
            }
        }
    }


    fun checkInputDateValid(tvTimeStart: EditText, tvTimeEnd: EditText) {
        val dateStringStart = tvTimeStart.text.toString().trim { it <= ' ' }
        val dateStringEnd = tvTimeEnd.text.toString().trim { it <= ' ' }
        val validStart = isValid(dateStringStart, yearMonthDayStr)
        val validEnd = isValid(dateStringEnd, yearMonthDayStr)
        if (!validStart) {
            //mBinding.tvTimeStart.setText(getTimeStartEndValue(true));
            tvTimeStart.text = null
        }
        if (!validEnd) {
            //mBinding.tvTimeEnd.setText(getTimeStartEndValue(false));
            tvTimeEnd.text = null
        }
    }

    private fun helperActionSearch(index: Int) {
        if (index < 0 || index > mMaxPageCount) return
        if (null != mFootSearchCallback) {
            currentIndex = index
            mFootPageView!!.mEtJumpToValue.setText("${currentIndex + 1}")
            mFootSearchCallback!!.onActionSearch(index)
        }
    }

    fun onDestroyView() {
        mFootSearchCallback = null
        mFootPageView = null
    }

    fun resetValue() {
        hideCloseKeyBoard(mFootPageView!!.mTvTotalItem)

        currentIndex = 0
        mTotalItemCountInDatabase = 0
        mMaxPageCount = 0
    }


    fun hideCloseKeyBoard(view: View) {
        val imm =
            getApplication().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    fun getMaxPage(totalCountInDB: Int): Int {
        if (totalCountInDB <= perPageCount) {
            return 0
        }
        return totalCountInDB / perPageCount

    }

    fun setFootValue(theTotalCount: Int, pageIndex: Int) {
        mTotalItemCountInDatabase = theTotalCount
        mMaxPageCount = getMaxPage(mTotalItemCountInDatabase)
        if (theTotalCount == 0) {
            currentIndex = 0
            mTotalItemCountInDatabase = 0
            mMaxPageCount = 0
        }
        //
        mFootPageView!!.mTvTotalItem.text =
            mFootPageView!!.resources.getString(R.string.item_xx_total, mTotalItemCountInDatabase)
    }

    /**
     * 从 参考 FileDao_Impl
     */
    fun getTheTotalCount(_cursor: Cursor): Int {
        try {
            val _result = if (_cursor.moveToFirst()) {
                _cursor.getInt(0)
            } else {
                0
            }
            return _result
        } finally {
            _cursor.close()
        }
    }

    fun isValid(dateStr: String, simpleDateFormatStr: String?): Boolean {
        val sdf: DateFormat = SimpleDateFormat(simpleDateFormatStr, Locale.CHINA)
        sdf.isLenient = false
        try {
            sdf.parse(dateStr)
        } catch (e: ParseException) {
            return false
        }
        return true
    }

    fun getTimeStamp(isStart: Boolean, dateStringStartYearMonthDay: String): Long {
        val valid = isValid(dateStringStartYearMonthDay, yearMonthDayStr)
        if (!valid) {
            return 0
        }

        if (!TextUtils.isEmpty(dateStringStartYearMonthDay)) {
            var endDate: Date? = null
            try {
                endDate = yearMonthDay.parse(dateStringStartYearMonthDay)
                yearMonthDay.isLenient = false
            } catch (e: ParseException) {
                //throw new RuntimeException(e);
                return 0
            }
            if (null != endDate) {
                val loginTimeStampEnd = endDate.time
                return if (isStart) {
                    loginTimeStampEnd
                } else {
                    loginTimeStampEnd + oneDayMillSec_subtract_1
                }
            }
        }


        return 0
    }

    fun showFirstPage() {
//        resetValue()
        helperActionSearch(0)
    }

    fun showLastPage() {
        helperActionSearch(mMaxPageCount)
    }

    interface OnItemClickListener {
        fun onItemClickEdit(position: Int)
        fun onItemClickDelete(position: Int)
    }

    interface FootSearchCallback {
        fun onActionSearch(index: Int)
    }

    companion object {
        const val perPageCount: Int = 10
        var yearMonthDayStr: String = "yyyy/MM/dd"
        var oneDayMillSec_subtract_1: Long = (24 * 60 * 60 * 1000 - 1).toLong()
        val EARLY_WARNING_TIME_END_PLUS: Long = oneDayMillSec_subtract_1 * 2

        /**
         * 判断一个数字是奇数还是偶数
         *
         * @param number 需要判断的数字
         * @return true偶数, false奇数
         */
        fun isEvenOrOdd(number: Int): Boolean {
            return if ((number and 1) == 0) {
                true
            } else {
                false
            }
        }
    }
}
